package com.example.mongologistics.service.impl;

import com.example.mongologistics.pojo.Logistics;
import com.example.mongologistics.pojo.Order;
import com.example.mongologistics.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("orderService")
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Override
    public void addOrder(Order order) {
        Order order1=null;
        try {
            order1 = mongoTemplate.insert(order, "order");
        } catch (Exception e) {
            log.info("订单添加失败");
            return;
        }
        log.info("订单添加成功"+order1);
    }


    @Override
    public void addLogisticsAndUpdateStatus(Logistics logistics) {
        String status = logistics.getOperation();
        Query query = new Query(Criteria.where("_id").is(logistics.getOrderId()));
        Update update = new Update();
        update.set("status", status);
        update.push("logisticsList", logistics);
        mongoTemplate.upsert(query, update, Order.class);
    }


    //通过id查询物流
    @Override
    public Order getOrderById(int id)
    {
        Query query = new Query(Criteria.where("_id").is(id));
        Order order=mongoTemplate.findOne(query, Order.class);
        return order;
    }

    @Override
    public boolean deleteOrderById(int id) {
        Query query = new Query(Criteria.where("_id").is(id));
        mongoTemplate.remove(query, Order.class, "order");
        return true;
    }

    @Override
    public List<Order> getAllOrders() {
        List<Order> orderList = mongoTemplate.findAll(Order.class, "order");
        return orderList;
    }
}
